package com.codeest.geeknews.util.notify;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;

import com.codeest.geeknews.R;
import com.codeest.geeknews.util.okhttp.DownloadInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * 下载通知管理工具类
 *
 * @author ldm
 * @description：
 * @date 2016-5-3 上午9:39:56
 */
public class DownloadNotifyManager {
    private AbstractFactory notifyFactory;
    // DownloadNotifyManager ： 是状态栏通知的管理类，负责发通知、清楚通知等。
    private NotificationManager manager;
    // 定义Map来保存Notification对象
    private Map<Integer, NotificationCompat.Builder> builderMap = null;
    private Map<Integer, Notification> notificationMap = null;

    private Context context;

    public DownloadNotifyManager(Context context) {
        this.context = context;
        notifyFactory = new NotifyFactory();
        manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        builderMap = new HashMap<>();
        notificationMap = new HashMap<>();
    }

    public void showNotification(int notificationId, DownloadInfo downloadInfo) {
        // 判断对应id的Notification是否已经显示， 以免同一个Notification出现多次
        if (!notificationMap.containsKey(notificationId)) {
            DownloadNotifyBuilder builder = notifyFactory.createDownloadNotify(context,downloadInfo);
            Notification notification = builder.build();
            manager.notify(notificationId, notification);
            builderMap.put(notificationId, builder);// 存入Map中
            notificationMap.put(notificationId, notification);// 存入Map中
        }
    }

    public void updateProgress(int notificationId, int progress) {
        NotificationCompat.Builder notifyBuilder = builderMap.get(notificationId);
        Notification notify = notificationMap.get(notificationId);
        if (null != notify) {
            // 修改进度条
            notifyBuilder.getContentView().setProgressBar(R.id.pBar, 100, progress, false);
            @SuppressLint("DefaultLocale") String progressText = String.format("%d%%", progress);
            notifyBuilder.getContentView().setTextViewText(R.id.tv_progress, progressText);
            manager.notify(notificationId, notify);
        }
    }

    public void remove(int notificationId) {
        manager.cancel(notificationId);
        builderMap.remove(notificationId);
        notificationMap.remove(notificationId);
    }
}